<?php

namespace G\User\Model;

use Core\Database\Eloquent\Model;
use Core\Support\Encrypt;
use Illuminate\Database\Eloquent\SoftDeletes;

class UserModel extends Model
{
    use SoftDeletes;

    protected $table = 'g_user';
    protected $dateFormat = 'U';

    const CREATED_AT = 'ct';
    const UPDATED_AT = 'ut';
    const DELETED_AT = 'dt';

    const STATE_ENABLED   = 1;      // 可用
    const STATE_NOTLOGIN  = 2;      // 不可登录
    const STATE_DISABLE   = 4;      // 禁用(封号)

    // 可批量赋值的属性
    protected $fillable = [
        'name',
        'avatar',
        'gender',
        'phone',
        'mail',
    ];

    // 默认值
    protected $attributes = [
        'state' => self::STATE_ENABLED,
    ];

    protected $hidden = [
        'password_hash',
        'dt',
    ];

    protected $casts = [
        'ct' => 'datetime:Y-m-d H:i:s',
        'ut' => 'datetime:Y-m-d H:i:s',
    ];

    /**
     * 是否是测试账户, 用户测试环境
     */
    public static function inTest($uid)
    {
        $testIds = [9527];

        if (in_array($uid, $testIds)) {
            return true;
        }

        return false;
    }

    public function setPassword($password)
    {
        $this->password_hash = Encrypt::passwordHash($password);
    }

    public function authentication($pass)
    {
        if ($this->state == self::STATE_ENABLED) {
            return Encrypt::authentication($pass, $this->password_hash);
        }

        return false;
    }

    /**
     * 检查用户是否有效
     */
    public function isEnabled()
    {
        if ($this->state == self::STATE_ENABLED) {
            return true;
        }

        return false;
    }
}
